/*!
 * TODO 增加距离设置
 *
 * http://www.zhangxinxu.com/wordpress/2010/11/jquery%E9%A1%B5%E9%9D%A2%E5%9B%BE%E7%89%87%E7%AD%89%E5%85%83%E7%B4%A0%E6%BB%9A%E5%8A%A8%E5%8A%A8%E6%80%81%E5%8A%A0%E8%BD%BD%E5%AE%9E%E7%8E%B0/
 * <div class="scrollLoading" data-url="loaded.html">加载中...</div>
 * jquery.scrollLoading.js
 * by zhangxinxu http://www.zhangxinxu.com/wordpress/?p=1259
 * 2010-11-19 v1.0
 * 2012-01-13 v1.1 偏移值计算修改 position → offset
 * 2012-09-25 v1.2 增加滚动容器参数, 回调参数
 * 2014-08-11 v1.3 修复设置滚动容器参数一些bug, 以及误删posb值的一些低级错误
 */
(function ($) {
    $.fn.lazyload = function (options) {
        var defaults = {
            attr: "data-lazyload-src",
            container: $(window),
            callback: $.noop
        };
        var params = $.extend({}, defaults, options || {});

        params.cache = [];
        $(this).each(function () {
            var node = this.nodeName.toLowerCase(),
                url = $(this).attr(params["attr"]);

            //重组
            var data = {
                el: $(this),
                tag: node,
                url: url
            };
            params.cache.push(data);
        });

        var callback = function (call) {
            if ($.isFunction(params.callback)) {
                params.callback.call(call.get(0));
            }
        };

        //动态显示数据
        var loading = function () {
            var contHeight = params.container.height();
            if (params.container.get(0) === window) {
                contop = $(window).scrollTop();
            } else {
                contop = params.container.offset().top;
            }

            $.each(params.cache, function (i, data) {
                var el = data.el,
                    tag = data.tag,
                    url = data.url, post, posb;

                if (el) {
                    post = el.offset().top - contop, posb = post + el.height();
                    if ((post >= 0 && post < contHeight) || (posb > 0 && posb <= contHeight)) {
                        if (url) {
                            //在浏览器窗口内
                            if (tag === "img") {
                                console.log('load');
                                //图片，改变src
                                callback(el.attr("src", url));
                            } else {
                                el.load(url, {}, function () {
                                    callback(el);
                                });
                            }
                        } else {
                            // 无地址，直接触发回调
                            callback(o);
                        }
                        data.obj = null;
                    }
                }
            });
        };

        //事件触发
        //加载完毕即执行
        loading();
        //滚动执行
        params.container.bind("scroll", loading);
    };
})(jQuery);